package com.apes.framework.plugin.form.parser.element;

import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.form.parser.node.FormNodeParser;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 功能：split解析
 *
 * @author xul
 * @create 2018-09-15 10:44
 */
@Component
public class SplitElementParser extends AbstractElementParser {

    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"split"};

    /**
     * 功能：可解析节点域
     */
    @Override
    public String getDomain() {
        return FormNodeParser.domain;
    }

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }

    @Override
    public Map parse(ApesElement element) {
        Map node = new HashMap();
        element.getAttributes().forEach((k, v) -> {
            node.put(k, v);
        });
        if (isSplits(element)) {
            node.put("genre", "split");
            List<Map> children = new ArrayList<>();
            element.getNestedElements().forEach((apesElement) -> {
                children.add(apesElement.parse());
            });
            node.put("renderData", children);
        } else {
            node.put("fields", element.getNestedElements().stream()
                    .map(new Function<ApesElement, Object>() {
                        @Override
                        public Object apply(ApesElement apesElement) {
                            return apesElement.parse();
                        }
                    }).collect(Collectors.toList()));
        }
        return node;
    }

    private boolean isSplits(ApesElement element) {
        return element.getNestedElements().stream().filter(e -> e.getName().equals("split")).count() > 0;
    }

}
